#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
生成OpenBMC ABI汇总报告

功能：
1. 汇总所有库的ABI统计信息
2. 生成总览Excel表格
3. 按优先级排序
"""

import json
import sys
from pathlib import Path
import pandas as pd
from openpyxl import load_workbook
from openpyxl.styles import Font, PatternFill, Alignment


def main():
    """生成汇总报告"""
    project_root = Path(__file__).parent.parent.parent
    abi_dir = project_root / 'output' / 'abi_data'
    output_file = project_root / 'output' / 'OPENBMC_ABI_SUMMARY.xlsx'
    
    print("[INFO] 读取所有ABI数据...")
    
    # 收集所有库的信息
    libraries_data = []
    all_symbols = []
    
    for json_file in sorted(abi_dir.glob('*.json')):
        with open(json_file, 'r', encoding='utf-8') as f:
            data = json.load(f)
            
            lib_info = data['library']
            stats = data['statistics']
            
            # 添加库信息
            libraries_data.append({
                '库名': lib_info['name'],
                '大小(MB)': round(lib_info['size'] / 1024 / 1024, 2),
                '架构': lib_info['architecture'],
                '总符号数': stats['total_symbols'],
                '函数': stats['functions'],
                '对象': stats['objects'],
                'C++符号': stats['cpp_symbols'],
                'C符号': stats['c_symbols'],
                '命名空间': stats['unique_namespaces'],
                '类数量': stats['unique_classes'],
                '构造函数': stats['constructors'],
                '析构函数': stats['destructors'],
                '模板': stats['templates'],
                'const函数': stats['const_functions'],
                '调试信息': '是' if lib_info['has_debug_info'] else '否',
                '依赖数': len(lib_info['dependencies']),
            })
            
            # 收集所有符号（用于后续分析）
            for symbol in data['symbols']:
                all_symbols.append({
                    '库名': lib_info['name'],
                    '符号名': symbol['name'],
                    '解析后': symbol['demangled_name'],
                    '类型': symbol['symbol_type'],
                    '命名空间': symbol.get('namespace', ''),
                    '类名': symbol.get('class_name', ''),
                    '函数名': symbol.get('function_name', ''),
                })
    
    print(f"[INFO] 共读取 {len(libraries_data)} 个库，{len(all_symbols)} 个符号")
    
    # 创建Excel文件
    print("[INFO] 生成汇总Excel...")
    
    with pd.ExcelWriter(output_file, engine='openpyxl') as writer:
        # Sheet 1: 库汇总（按符号数排序）
        df_libs = pd.DataFrame(libraries_data)
        df_libs_sorted = df_libs.sort_values('总符号数', ascending=False)
        df_libs_sorted.insert(0, '排名', range(1, len(df_libs_sorted) + 1))
        df_libs_sorted.to_excel(writer, sheet_name='库汇总_按符号数', index=False)
        
        # Sheet 2: 库汇总（按大小排序）
        df_libs_by_size = df_libs.sort_values('大小(MB)', ascending=False)
        df_libs_by_size.insert(0, '排名', range(1, len(df_libs_by_size) + 1))
        df_libs_by_size.to_excel(writer, sheet_name='库汇总_按大小', index=False)
        
        # Sheet 3: 总体统计
        total_stats = pd.DataFrame([{
            '指标': '总库数',
            '数值': len(libraries_data)
        }, {
            '指标': '总大小(MB)',
            '数值': round(sum(d['大小(MB)'] for d in libraries_data), 2)
        }, {
            '指标': '总符号数',
            '数值': sum(d['总符号数'] for d in libraries_data)
        }, {
            '指标': '总函数数',
            '数值': sum(d['函数'] for d in libraries_data)
        }, {
            '指标': 'C++符号',
            '数值': sum(d['C++符号'] for d in libraries_data)
        }, {
            '指标': 'C符号',
            '数值': sum(d['C符号'] for d in libraries_data)
        }, {
            '指标': '平均符号/库',
            '数值': round(sum(d['总符号数'] for d in libraries_data) / len(libraries_data), 1)
        }])
        total_stats.to_excel(writer, sheet_name='总体统计', index=False)
        
        # Sheet 4: 命名空间统计
        namespace_stats = {}
        for symbol in all_symbols:
            ns = symbol['命名空间']
            if ns:
                if ns not in namespace_stats:
                    namespace_stats[ns] = 0
                namespace_stats[ns] += 1
        
        if namespace_stats:
            ns_df = pd.DataFrame([
                {'命名空间': k, '符号数': v} 
                for k, v in sorted(namespace_stats.items(), key=lambda x: x[1], reverse=True)
            ])
            ns_df.insert(0, '排名', range(1, len(ns_df) + 1))
            ns_df.to_excel(writer, sheet_name='命名空间统计', index=False)
        
        # Sheet 5: Top 100 函数（按名称）
        functions = [s for s in all_symbols if s['类型'] == 'function'][:100]
        if functions:
            func_df = pd.DataFrame(functions)
            func_df.insert(0, '序号', range(1, len(func_df) + 1))
            func_df.to_excel(writer, sheet_name='Top100函数', index=False)
        
        # Sheet 6: 依赖关系矩阵
        dep_matrix_data = []
        for json_file in sorted(abi_dir.glob('*.json')):
            with open(json_file, 'r') as f:
                data = json.load(f)
                lib_name = data['library']['name']
                deps = data['library']['dependencies']
                dep_matrix_data.append({
                    '库名': lib_name,
                    '依赖库': ', '.join(deps) if deps else '无'
                })
        
        dep_df = pd.DataFrame(dep_matrix_data)
        dep_df.to_excel(writer, sheet_name='依赖关系', index=False)
    
    # 美化Excel
    print("[INFO] 美化Excel表格...")
    wb = load_workbook(output_file)
    
    header_fill = PatternFill(start_color="366092", end_color="366092", fill_type="solid")
    header_font = Font(bold=True, color="FFFFFF")
    
    for sheet in wb.worksheets:
        # 设置表头样式
        for cell in sheet[1]:
            cell.fill = header_fill
            cell.font = header_font
            cell.alignment = Alignment(horizontal='center', vertical='center')
        
        # 自动调整列宽
        for column in sheet.columns:
            max_length = 0
            column_letter = column[0].column_letter
            for cell in column:
                try:
                    if cell.value:
                        max_length = max(max_length, len(str(cell.value)))
                except:
                    pass
            adjusted_width = min(max_length + 2, 80)
            sheet.column_dimensions[column_letter].width = adjusted_width
    
    wb.save(output_file)
    
    print(f"[SUCCESS] 汇总报告已生成: {output_file}")
    print("\n" + "=" * 80)
    print("汇总统计:")
    print(f"  总库数: {len(libraries_data)}")
    print(f"  总大小: {sum(d['大小(MB)'] for d in libraries_data):.2f} MB")
    print(f"  总符号数: {sum(d['总符号数'] for d in libraries_data):,}")
    print(f"  总函数数: {sum(d['函数'] for d in libraries_data):,}")
    print("=" * 80)
    
    return 0


if __name__ == '__main__':
    sys.exit(main())

